package project.rbac.view;

import project.rbac.domain.dto.UserDto;
import project.rbac.domain.vo.DeptVo;
import project.rbac.domain.vo.Result;
import project.rbac.domain.vo.RoleVo;
import project.rbac.domain.vo.UserVo;
import project.rbac.exception.ExceptionHandler;
import project.rbac.service.IUserService;
import project.rbac.service.impl.UserService;
import project.rbac.util.DateTimeUtils;
import project.rbac.util.SingletonFactory;

public class UserView extends BaseView<UserVo, IUserService> {

    public static final String MENU = """
            -------------------
                 用户管理
            -------------------
            |   0   返回上级    |
            |   1   用户列表    |
            |   2   创建用户    |
            |   3   更新用户    |
            |   4   切换状态    |
            |   5   修改密码    |
            -------------------
            请输入选项：""";

    private final DeptView deptView;
    private final RoleView roleView;

    private UserView() {
        deptView = SingletonFactory.getInstance(DeptView.class);
        roleView = SingletonFactory.getInstance(RoleView.class);
        service = SingletonFactory.getInstance(UserService.class);
    }

    /**
     * 显示界面
     */
    public void show() {
        do {
            try {
                System.out.print(MENU);
                String menuChoice = MainView.input.nextLine();
                switch (menuChoice) {
                    case "0" -> {
                        System.out.println("已返回上一级菜单！");
                        return;
                    }
                    case "1" -> list();
                    case "2" -> create();
                    case "3" -> update();
                    case "4" -> toggle();
                    case "5" -> changePassword();
                    default -> System.out.println("输入非法，请输入正确的菜单编号！");
                }
            } catch (Exception e) {
                ExceptionHandler.handle(e);
            }
        } while (true);
    }

    public void list() {
        Result result = service.list();
        cache = (UserVo[]) result.data;
        System.out.println("ID\t用户名\t姓名\t手机\t邮箱\t部门名称\t角色名称\t状态\t更新时间");
        for (UserVo user : cache) {
            System.out.printf("%d\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n", user.id, user.username, user.name,
                    user.mobile, user.email, user.deptName, user.roleName, user.enabled ? "启用" : "停用",
                    DateTimeUtils.format(user.updateAt));
        }
    }

    public void create() {
        System.out.print("请输入用户名：");
        String username = MainView.input.nextLine();
        System.out.print("请输入姓名：");
        String name = MainView.input.nextLine();
        System.out.print("请输入手机号：");
        String mobile = MainView.input.nextLine();
        System.out.print("请输入邮箱：");
        String email = MainView.input.nextLine();
        System.out.print("设置密码: ");
        String password = MainView.input.nextLine();
        System.out.println("请选择部门ID：");
        int deptId = 0;
        do {
            deptView.list();
            if (deptView.cache == null || deptView.cache.length == 0) {
                printError("系统还没有创建任何部门信息，请先创建部门信息。");
                return;
            }
            DeptVo dept = deptView.getCacheById();
            if (dept != null) {
                deptId = dept.id;
            }
        } while (deptId == 0);
        System.out.println("请选择角色ID：");
        int roleId = 0;
        do {
            roleView.list();
            if (roleView.cache == null || roleView.cache.length == 0) {
                printError("系统还没有创建任何角色信息，请先创建角色信息。");
                return;
            }
            RoleVo role = roleView.getCacheById();
            if (role != null) {
                roleId = role.id;
            }
        } while (roleId == 0);
        UserDto dto = new UserDto(username, name, mobile, email, deptId, roleId, password);
        Result result = service.create(dto);
        if (!result.success) {
            printError(result.message);
            return;
        }
        System.out.println(result.message);
        list();
    }

    public void update() {
        UserVo user = getCacheById();
        if (user == null) {
            return;
        }
        System.out.print("输入当前密码验证: ");
        String password = MainView.input.nextLine();

        if (!service.verifyPassword(user.id, password)) {
            printError("密码错误，更新操作被拒绝");
            return;
        }

        System.out.print("请输入用户名，直接按回车表示不修改：");
        String username = MainView.input.nextLine();
        username = "".equals(username) ? user.username : username;

        System.out.print("请输入姓名，直接按回车表示不修改：");
        String name = MainView.input.nextLine();
        name = "".equals(name) ? user.name : name;

        System.out.print("请输入手机号码，直接按回车表示不修改：");
        String mobile = MainView.input.nextLine();
        mobile = "".equals(mobile) ? user.mobile : mobile;

        System.out.print("请输入邮箱，直接按回车表示不修改：");
        String email = MainView.input.nextLine();
        email = "".equals(email) ? user.email : email;

        System.out.println("请选择部门ID：");
        int deptId = 0;
        do {
            deptView.list();
            if (deptView.cache == null || deptView.cache.length == 0) {
                printError("系统还没有创建任何部门信息，请先创建部门信息。");
                return;
            }
            DeptVo dept = deptView.getCacheById();
            if (dept != null) {
                deptId = dept.id;
            }
        } while (deptId == 0);
        System.out.println("请选择角色ID：");
        int roleId = 0;
        do {
            roleView.list();
            if (roleView.cache == null || roleView.cache.length == 0) {
                printError("系统还没有创建任何角色信息，请先创建角色信息。");
                return;
            }
            RoleVo role = roleView.getCacheById();
            if (role != null) {
                roleId = role.id;
            }
        } while (roleId == 0);

        UserDto dto = new UserDto(username, name, mobile, email, deptId, roleId, password);
        Result result = service.update(dto, user.id);
        if (!result.success) {
            printError(result.message);
            return;
        }
        System.out.println(result.message);
        list();
    }

    public void toggle() {
        UserVo user = getCacheById();
        if (user == null) {
            return;
        }
        if (user.enabled) {
            System.out.print("输入‘Y’确认停用，输入其他则取消停用：");
        } else {
            System.out.print("输入‘Y’确认启用，输入其他则取消启用：");
        }
        String confirm = MainView.input.nextLine();
        if (!"Y".equalsIgnoreCase(confirm)) {
            System.out.println("您已取消修改状态的操作");
            return;
        }
        Result result = service.toggle(user.id);
        if (!result.success) {
            printError(result.message);
            return;
        }
        System.out.println(result.message);
        list();
    }
    public void changePassword() {
        UserVo user = getCacheById();
        if (user == null) {
            return;
        }
        System.out.print("请输入旧密码：");
        String oldPassword = MainView.input.nextLine();
        System.out.print("请输入新密码：");
        String newPassword = MainView.input.nextLine();
        Result result = service.changePassword(user.id, oldPassword, newPassword);
        if (!result.success) {
            System.out.println("密码修改失败: " + result.message);
            return;
        }
        System.out.println("密码修改成功");
    }
}
